#include "GameObject.h"
#include "Cell.h"

GameObject::GameObject(): cell(0)
{
}


GameObject::~GameObject()
{
	Clear();
}

void GameObject::Clear()
{
	ClearHandlers();
	ClearCell();
}

void GameObject::ClearCell()
{
	if (cell)
	{	
		cell->Remove(this);

		cell = 0;
	}
}

void GameObject::ClearHandlers()
{
	std::list<GameEventHandler*>::iterator it;

	for(it = eventHandlers.begin(); it != eventHandlers.end(); ++it)
	{
		delete (*it);
	}

	eventHandlers.clear();
}

void GameObject::AddEventHandler(GameEventHandler* handler)
{
	eventHandlers.push_back( handler->Clone() );
}

bool GameObject::CanHandle(GameEvent* gameEvent)
{
	std::list<GameEventHandler*>::iterator it;

	for(it = eventHandlers.begin(); it != eventHandlers.end(); ++it)
	{
		if ( (*it)->CanHandle(gameEvent) )
			return true;
	}

	return false;
}

bool GameObject::HandleEvent(GameEvent* gameEvent)
{
	std::list<GameEventHandler*>::iterator it;

	for(it = eventHandlers.begin(); it != eventHandlers.end(); ++it)
	{
		if ( (*it)->CanHandle(gameEvent) )
		{
			(*it)->HandleEvent(gameEvent);

			return true;
		}
	}

	return false;
}



void GameObject::MoveToCell(Cell* newCell, unsigned int cellX, unsigned int cellY)
{
	if (newCell != cell)
	{
		if (cell)
		{
			cell->Remove(this);
		}

		cell = newCell;

		if (cell)
		{
			cell->Add(this);
		}
	}

	cellPositionX = cellX;
	cellPositionY = cellY;
}


unsigned int GameObject::CellX() const
{
	return cellPositionX;
}

unsigned int GameObject::CellY() const
{
	return cellPositionY;
}

Cell* GameObject::GetCell() const
{
	return cell;
}

void GameObject::SetNullCell()
{
	cell = 0;
}

void GameObject::SetCellY(unsigned int cellY)
{
	cellPositionY = cellY;
}

void GameObject::SetCellX(unsigned int cellX)
{
	cellPositionX = cellX;
}
